import React from 'react';
import styles from './itemAttendance.less';
import {
  DatePicker,
  Space,
  Button,
  Input,
  Table,
  Form,
  Select,
  message,
  Spin,
} from 'antd';
import { Link } from 'react-router-dom';

import { CourseEditObject } from '@/pages/admin/course/cEdit';
import request from '@/http';
import qs from 'qs';

const { RangePicker } = DatePicker;
const { Option } = Select;
import {
  getCollage,
  getTeacher,
  getClasses,
  getGrade,
  getMajor,
  getCourse,
  getTeam,
} from '@/pages/admin/pulic';

export default () => {
  const [aReasonObject, setAReasonObject] = React.useState<CourseEditObject>({
    isModalVisible: false,
  });

  const [formObject] = Form.useForm();
  const [loadingState, setLoadingState] = React.useState({ loading: true });
  const [searchValue, setSearchValue] = React.useState('');
  const [dataSource, setDataSource] = React.useState<any[]>([]);
  const [pagination, setPagination] = React.useState({
    current: 1,
    total: 10,
    pageSize: 10,
    showSizeChanger: true,
    pageSizeOptions: ['10', '50', '200', '500'],
    showQuickJumper: true,
  });
  const loadDataSource = async (
    userParams: any,
    pageValue: any,
    pageSize: any,
  ) => {
    const ds = {
      ...userParams,
      currentPage: pageValue,
      size: pageSize,
    };
    const result: any = await request.post(
      '/api/admin/attendance/SelAttendance',
      qs.stringify(ds),
    );
    console.log('考勤记录：', result);
    console.log(444444);
    if (result && result.code === 200) {
      const data: any = result.data.data.map((user: any) => ({
        key: `user_${user.id}`,
        id: user.id,
        className: user.className, //班级名
        collegesName: user.collegesName, //学院名
        courseName: user.courseName, //	课程名
        gradeName: user.gradeName, //年级名
        teamName: user.teamName, //小组名
        majorName: user.majorName, //专业名
        dutyTeacher: user.dutyTeacher, //责任老师
        searcherEndTime: user.searcherEndTime, //搜索结束时间
        searcherStartTime: user.searcherStartTime, //搜索开始时间
        projectDate: user.projectDate, //日期
        studentName: user.studentName, //学生名
        userNo: user.userNo, //	学生学号
        trainTeacher: user.trainTeacher, //	实训老师
        attendanceType: user.attendanceType, //考勤情况：0 正常 1 迟到 2 早退 3 请假 4 缺勤
        signInTime: user.signInTime, //
        signOutTime: user.signOutTime, //
        realStartTime: user.realStartTime, //
        realEndTime: user.realEndTime, //
      }));

      const newPageObject = {
        ...pagination,
        current: pageValue,
        pageSize: pageSize,
        total: result.data.total, //总条数 分页               *******************
      };

      console.log(result.data.total);
      setPagination(newPageObject);
      setDataSource(data);
      setLoadingState({ loading: false });
    }
  };

  const cCollege = localStorage.getItem('collegesName');
  if (cCollege != null) {
    var cCollegeData = JSON.parse(cCollege);
  }
  const cGrade = localStorage.getItem('gradeName');
  if (cGrade != null) {
    var cGradeData = JSON.parse(cGrade);
  }
  let cClass = localStorage.getItem('classname');
  if (cClass != null) {
    var cClassData = JSON.parse(cClass);
  }
  let cMajor = localStorage.getItem('major');
  if (cMajor != null) {
    var cMajorData = JSON.parse(cMajor);
  }
  let cTeacher = localStorage.getItem('teacher');
  if (cTeacher != null) {
    var cTeacherData = JSON.parse(cTeacher);
  }
  let cTeam = localStorage.getItem('team');
  if (cTeam != null) {
    var cTeamData = JSON.parse(cTeam);
  }

  let cCourse = localStorage.getItem('course');
  if (cCourse != null) {
    var cCourseData = JSON.parse(cCourse);
  }

  //搜索
  const searchOnClick = async () => {
    setLoadingState({ loading: true });
    console.log(formObject.getFieldsValue());
    const data = await formObject.validateFields();
    let dataStr = '';
    const data2 = {
      attendanceType: data.attendanceType.toString(),
      className: data.className,
      collegesName: data.collegesName,
      courseName: data.courseName,
      dutyTeacher: data.dutyTeacher,
      gradeName: data.gradeName,
      majorName: data.majorName,
      studentName: data.studentName,
      teamName: data.teamName,
      trainTeacher: data.trainTeacher,
      userNo: data.userNo,
    };
    const ds = {
      ...data2,
      startDate: data.projectDate
        ? data.projectDate[0].format('yyyy-MM-DD')
        : '',
      endDate: data.projectDate ? data.projectDate[1].format('yyyy-MM-DD') : '',
    };
    // console.log('考勤查询：', ds);
    await loadDataSource(ds, 1, pagination.pageSize);
  };

  //生命周期函数
  React.useEffect(() => {
    if (!cGradeData) getGrade();
    if (!cCollegeData) getCollage();
    if (!cClassData) getClasses();
    if (!cMajorData) getMajor();
    if (!cCourseData) getCourse();
    if (!cTeamData) getTeam();
    if (!cTeacherData) getTeacher();
    loadDataSource(null, 1, pagination.pageSize);
  }, []);

  //换页
  const pageOnChange = async (page: any) => {
    await loadDataSource(
      formObject.getFieldsValue(),
      page.current,
      page.pageSize,
    );
  };

  return (
    <div className="pageMain">
      <div className="pageContent">
        <div
          className="search"
          style={{
            width: 1400,
            display: 'flex',
            flexDirection: 'row-reverse',
            justifyContent: 'space-around',
          }}
        >
          <div className={styles.searchForm}>
            <Form
              layout="inline"
              style={{ marginBottom: 10 }}
              form={formObject}
            >
              <Form.Item
                label="日&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;期"
                name="projectDate"
              >
                <RangePicker
                  format="YYYY-MM-DD"
                  style={{ width: 220 }}
                  className="itemAttendanceSelect"
                />
              </Form.Item>
              <Form.Item
                label="院&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;系"
                name="collegesName"
                initialValue=""
              >
                <Select className="itemAttendanceSelect mLeft">
                  <Option value="">请选择...</Option>
                  {cCollegeData
                    ? cCollegeData.map((item: any, index: any) => {
                        return (
                          <Option
                            index={index}
                            key={index}
                            value={item.collegeName}
                            children={item.collegeName}
                          />
                        );
                      })
                    : ''}
                </Select>
              </Form.Item>

              <Form.Item
                label="专&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;业"
                name="majorName"
                initialValue=""
              >
                <Select className="itemAttendanceSelect mLeft">
                  <Option value="">请选择...</Option>
                  {cMajorData
                    ? cMajorData.map((item: any, index: any) => {
                        return (
                          <Option
                            index={index}
                            key={index}
                            value={item.majorName}
                            children={item.majorName}
                          />
                        );
                      })
                    : ''}
                </Select>
              </Form.Item>
              <Form.Item
                label="年&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;级"
                name="gradeName"
                initialValue=""
              >
                <Select className="itemAttendanceSelect mLeft">
                  <Option value="">请选择...</Option>
                  {cGradeData
                    ? cGradeData.map((item: any, index: any) => {
                        return (
                          <Option
                            index={index}
                            key={index}
                            value={item.gradeName}
                            children={item.gradeName}
                          />
                        );
                      })
                    : ''}
                </Select>
              </Form.Item>
              <Form.Item
                label="班&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;级"
                name="className"
                initialValue=""
              >
                <Select className="itemAttendanceSelect mLeft">
                  <Option value="">请选择...</Option>
                  {cClassData
                    ? cClassData.map((item: any, index: any) => {
                        return (
                          <Option
                            index={index}
                            key={index}
                            value={item.className}
                            children={item.className}
                          />
                        );
                      })
                    : ''}
                </Select>
              </Form.Item>
              <Form.Item label="小组名称" name="teamName" initialValue="">
                <Select className="itemAttendanceSelect mLeft">
                  <Option value="">请选择...</Option>
                  {cTeamData
                    ? cTeamData.map((item: any, index: any) => {
                        return (
                          <Option
                            index={index}
                            key={index}
                            value={item.teamName}
                            children={item.teamName}
                          />
                        );
                      })
                    : ''}
                </Select>
              </Form.Item>

              <Form.Item label="课程名称" name="courseName" initialValue="">
                <Select className="itemAttendanceSelect">
                  <Option value="">请选择...</Option>
                  {cCourseData
                    ? cCourseData.map((item: any, index: any) => {
                        return (
                          <Option
                            index={index}
                            key={index}
                            value={item.courseName}
                          >
                            {item.courseName}
                          </Option>
                        );
                      })
                    : ''}
                </Select>
              </Form.Item>
              <Form.Item
                label="学&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号"
                name="userNo"
              >
                <Input
                  allowClear
                  className="itemAttendanceInput mLeft"
                  placeholder="请输入..."
                />
              </Form.Item>

              <Form.Item label="责任老师" name="dutyTeacher" initialValue="">
                <Select className="itemAttendanceSelect">
                  <Option value="">请选择...</Option>
                  {cTeacherData
                    ? cTeacherData.map((item: any, index: any) => {
                        return (
                          <Option
                            index={index}
                            key={index}
                            value={item.teacherName}
                            children={item.teacherName}
                          />
                        );
                      })
                    : ''}
                </Select>
              </Form.Item>
              <Form.Item label="实训老师" name="trainTeacher" initialValue="">
                <Select className="itemAttendanceSelect">
                  <Option value="">请选择...</Option>
                  {cTeacherData
                    ? cTeacherData.map((item: any, index: any) => {
                        return (
                          <Option
                            index={index}
                            key={index}
                            value={item.teacherName}
                            children={item.teacherName}
                          />
                        );
                      })
                    : ''}
                </Select>
              </Form.Item>

              <Form.Item label="学生姓名" name="studentName">
                <Input
                  className="itemAttendanceInput"
                  placeholder="请输入..."
                  allowClear
                />
              </Form.Item>
              <Form.Item label="考勤情况" name="attendanceType" initialValue="">
                <Select
                  mode="tags"
                  className="itemAttendanceSelect"
                  placeholder="请选择..."
                  allowClear
                >
                  <Option value={1}>正常</Option>
                  <Option value={2}>迟到</Option>
                  <Option value={3}>早退</Option>
                  <Option value={4}>缺勤</Option>
                  <Option value={5}>请假</Option>
                </Select>
              </Form.Item>
              <Form.Item>
                <Button
                  // style={{ position: 'absolute', margin: '-20px 0 0 20px' }}
                  type="primary"
                  onClick={searchOnClick}
                >
                  查询
                </Button>
                <Button
                  style={{ marginLeft: '20px' }}
                  onClick={() => {
                    formObject.resetFields();
                  }}
                >
                  重置
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>

        <div className={styles.mainTable} style={{ width: 1600 }}>
          <Spin tip="Loading..." spinning={loadingState.loading}>
            <Table
              scroll={{ x: 'max-content' }}
              columns={[
                {
                  title: '日期',
                  dataIndex: 'projectDate',
                  key: 'projectDate',
                  width: 125,
                  align: 'center',
                },
                {
                  title: '院系',
                  dataIndex: 'collegesName',
                  key: 'collegesName',
                  width: 125,
                  align: 'center',
                },
                {
                  title: '专业',
                  dataIndex: 'majorName',
                  key: 'majorName',
                  width: 150,
                  align: 'center',
                },
                {
                  title: '年级',
                  dataIndex: 'gradeName',
                  key: 'gradeName',
                  width: 100,
                  align: 'center',
                },
                {
                  title: '班级',
                  dataIndex: 'className',
                  key: 'className',
                  width: 100,
                  align: 'center',
                },
                {
                  title: '小组',
                  dataIndex: 'teamName',
                  key: 'teamName',
                  width: 100,
                  align: 'center',
                },
                {
                  title: '课程名称',
                  dataIndex: 'courseName',
                  key: 'courseName',
                  width: 150,
                  align: 'center',
                },
                {
                  title: '实训老师',
                  dataIndex: 'trainTeacher',
                  key: 'trainTeacher',
                  width: 150,
                  align: 'center',
                },
                {
                  title: '责任老师',
                  dataIndex: 'dutyTeacher',
                  key: 'dutyTeacher',
                  width: 100,
                  align: 'center',
                },
                {
                  title: '姓名',
                  dataIndex: 'studentName',
                  key: 'studentName',
                  width: 100,
                  align: 'center',
                },
                {
                  title: '学号',
                  dataIndex: 'userNo',
                  key: 'userNo',
                  width: 125,
                  align: 'center',
                },
                {
                  title: '考勤情况',
                  dataIndex: 'attendanceType',
                  key: 'attendanceType',
                  width: 125,
                  align: 'center',
                  render: (attendanceType: string) =>
                    attendanceType == '1'
                      ? '正常'
                      : attendanceType == '2'
                      ? '迟到'
                      : attendanceType == '3'
                      ? '早退'
                      : attendanceType == '4'
                      ? '缺勤'
                      : '请假',
                },
                {
                  title: '应签到',
                  dataIndex: 'signInTime',
                  key: 'signInTime',
                  width: 125,
                  align: 'center',
                },
                {
                  title: '实签到',
                  dataIndex: 'realStartTime',
                  key: 'realStartTime',
                  width: 125,
                  align: 'center',
                },
                {
                  title: '应签退',
                  dataIndex: 'signOutTime',
                  key: 'signOutTime',
                  width: 125,
                  align: 'center',
                },
                {
                  title: '实签退',
                  dataIndex: 'realEndTime',
                  key: 'realEndTime',
                  width: 125,
                  align: 'center',
                },

                {
                  title: '操作',
                  key: 'action',
                  align: 'center',
                  width: 100,
                  render: (row: any) => {
                    return row.attendanceType == '5' ? (
                      <>
                        <Link
                          to={{
                            pathname: '/admin/attendance/absenceReason',
                            state: { ...row },
                          }}
                        >
                          <Button type="link">请假原因</Button>
                        </Link>
                      </>
                    ) : (
                      ''
                    );
                  },
                },
              ]}
              dataSource={dataSource}
              pagination={pagination}
              onChange={pageOnChange}
              tableLayout="fixed"
              bordered
            />
          </Spin>
        </div>
        {/*<AbsenceReason  editObject={aReasonObject} />*/}
      </div>
    </div>
  );
};
